<template>
  <x-breadcrumb :content-list="contentList"></x-breadcrumb> <!-- 面包屑导航 -->

  <el-card class="box-card mt-3">
    <div class="row border-1">
      <div class="col-3 d-flex">
        <x-search-input v-model="pageData.query" :inputBlurEvent="inputBlurEvent" :findBtnClick="findBtnClick"></x-search-input>
      </div>
      <div class="col-1">
        <el-button type="primary" @click="addProductEvent">添加用户</el-button>
      </div>
    </div>
    <el-table
      :data="userListData"
      border
      stripe
      class="my-3"
      style="width: 100%"
      :header-cell-style="{textAlign: 'center'}"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column type="index" label="#" />
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="mobile" label="电话" />
      <el-table-column prop="role_name" label="角色" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.mg_state" @change="tableInEvents.switchStateChanged(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template #default="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="tableInEvents.showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="tableInEvents.removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="tableInEvents.setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
      <x-pagubation :dispatch-name="'usersModule/getUsersPageData'" :total="total"></x-pagubation>
  </el-card>
  <el-dialog
    title="添加用户"
    v-model="AddUserData.addDialogVisible"
    :before-close="AddUserData.addHandleClose"
    width="50%"
  >
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="AddUserData.addHandleClose">取 消</el-button>
        <el-button type="primary" @click="AddUserData.add">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    title="编辑用户"
    v-model="changeUsers.changeUsersDialogVisible"
    :before-close="changeUsers.changeUsersHandleClose"
    width="50%"
  >
    <el-form :model="changeUsersForm" :rules="changeUsersFormRules" ref="changeUsersFormRef" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="changeUsersForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="changeUsersForm.mobile"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="changeUsersForm.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="changeUsers.changeUsersHandleClose">取 消</el-button>
        <el-button type="primary" @click="changeUsers.changeUsersSubmitClick">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    title="分配角色"
    v-model="AssignRolesObj.AssignRolesDialogVisible"
    :before-close="AssignRolesObj.AssignRolesHandleClose"
    width="50%"
  >
    <p class="fs-4">当前用户:&nbsp;&nbsp;{{AssignRolesObj.admin}}</p>
    <br>
    <p class="fs-4">当前角色:&nbsp;&nbsp;{{AssignRolesObj.roles}}</p>
    <br>
    <p class="fs-4">
      分配新角色:&nbsp;&nbsp;
      <el-select v-model="selectData.selectValue" placeholder="请选择">
        <el-option
          v-for="item in selectData.options"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </p>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="AssignRolesObj.AssignRolesHandleClose">取 消</el-button>
        <el-button type="primary" @click="AssignRolesObj.AssignRolesSubmitClick">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, computed, watchEffect, onMounted, ref, toRaw } from 'vue'
import XBreadcrumb, { contentType } from '@/components/public-components/XBreadcrumb.vue'
import XSearchInput from '@/components/public-components/XSearchInput.vue'
import XPagubation from '@/components/public-components/XPagination.vue'
import { messageBoxFunc } from '@/utils/el-messageBoxFunc'
import { objToArr } from '@/utils/helper'
import { useStore } from '@/store'
import { MessageFunc } from '@/utils/ElMessageFunc'

const checkEmail = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('邮箱不能为空'));
  }
  const emailReg = /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/;
  if (!emailReg.test(value)) {
    callback('邮箱不合法');
  } else {
    callback();
  }
};
const checkMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('手机号不能为空'));
  }
  const mobileReg = /^1[0-9]{10}$/;
  if (!mobileReg.test(value)) {
    callback('手机号不合法');
  } else {
    callback();
  }
};

const addFormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 10, message: `长度在 5 到 10 个字符`, trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 10, message: `长度在 5 到 10 个字符`, trigger: 'blur'}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {validator: checkMobile, trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'},
  ],
}

const changeUsersFormRules = {
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {validator: checkMobile, trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'},
  ]
}

const contentList: contentType[] = ['首页', '用户管理', '用户列表']

export default defineComponent({
  name: 'Users',
  components: {
    XBreadcrumb,
    XSearchInput,
    XPagubation
  },
  setup () {
    const store = useStore()
    const userListData = computed(() => objToArr(store.state.usersModule.usersData.users))
    const total = computed(() => store.state.usersModule.usersData.total)
    const userId = ref(0)
    const tableInEvents = reactive({
      switchStateChanged (row: any) {
        store.dispatch('usersModule/putUsersState', row).then(() => {
          store.dispatch('usersModule/getUsersPageData', { query: pageData.query, pageNum: pageData.pagenum, pageSize: pageData.pagesize })
        })
      },
      showEditDialog (rowId: any) {
        changeUsers.changeUsersDialogVisible = true
        userId.value = rowId
        const { username, mobile, email } = store.getters['usersModule/usersFindData'](rowId)
        changeUsersForm.username = username
        changeUsersForm.mobile = mobile
        changeUsersForm.email = email
      },
      setRole (row: any) {
        AssignRolesObj.admin = row.username
        AssignRolesObj.roles = row.role_name
        AssignRolesObj.rowId = row.id
        store.dispatch('usersModule/getRolesData')
        AssignRolesObj.AssignRolesDialogVisible = true
      },
      removeUserById (rowId: any) {
        console.log(rowId)
        messageBoxFunc('usersModule/deleteUser', store, { rowId }, () => store.dispatch('usersModule/getUsersPageData', { pageNum: pageData.pagenum, pageSize: pageData.pagesize }))
      }
    })
    onMounted(() => {
      store.dispatch('usersModule/getUsersPageData', { query: '', pageNum: 1, pageSize: 5 })
    })

    const pageData = reactive({
      query: '',
      pagenum: 1,
      pagesize: 5
    })
    const handleSizeChange = (val: number) => {
      pageData.pagesize = val
    };
    const handleCurrentChange = (val: number) => {
      pageData.pagenum = val
    };
    const findBtnClick = () => {
      if (pageData.query.trim()) {
        store.dispatch('usersModule/getUsersPageData', { query: pageData.query, pageNum: pageData.pagenum, pageSize: pageData.pagesize })
      }
    }
    const inputBlurEvent = () => {
      if (!pageData.query.trim()) {
        store.dispatch('usersModule/getUsersPageData', { pageNum: pageData.pagenum, pageSize: pageData.pagesize })
      }
    }
    watchEffect(() => {
      store.dispatch('usersModule/getUsersPageData', { pageNum: pageData.pagenum, pageSize: pageData.pagesize })
    })

    type validateType = {validate: (valid: any, obj?: any) => void}
    const AddUserData = reactive({ // 弹出框事件
      addDialogVisible: false,
      add () {
        (addFormRef.value as validateType).validate((valid: boolean) => {
          if (valid) {
            store.dispatch('usersModule/postAddUsersData', toRaw(addForm)).then(() => {
              store.dispatch('usersModule/getUsersPageData', { pageNum: pageData.pagenum, pageSize: pageData.pagesize })
            })
            MessageFunc('success', '添加成功')
            AddUserData.addDialogVisible = false
            addForm.username = ''
            addForm.password = ''
            addForm.mobile = ''
            addForm.email = ''
          } else {
            MessageFunc('warning', '表单格式不合法，请重新输入')
            AddUserData.addDialogVisible = false
            addForm.username = ''
            addForm.password = ''
            addForm.mobile = ''
            addForm.email = ''
          }
        })
        AddUserData.addDialogVisible = false
      },
      addHandleClose () {
        AddUserData.addDialogVisible = false
        addForm.username = ''
        addForm.password = ''
        addForm.mobile = ''
        addForm.email = ''
      }
    })
    const addForm = reactive({ // from表单
      username: '',
      password: '',
      mobile: '',
      email: ''
    })
    const addFormRef = ref< validateType | null>(null)
    const addProductEvent = () => { // 添加商品按钮
      AddUserData.addDialogVisible = true
    }

    const changeUsers = reactive({
      changeUsersDialogVisible: false,
      changeUsersHandleClose () {
        changeUsers.changeUsersDialogVisible = false
      },
      changeUsersSubmitClick () {
        store.dispatch('usersModule/putUserData', { rowId:  userId.value, data: toRaw(changeUsersForm)})
        changeUsers.changeUsersDialogVisible = false
      }
    })

    const changeUsersForm = reactive({
      username: '',
      mobile: '',
      email: ''
    })

    const AssignRolesObj = reactive({
      AssignRolesDialogVisible: false,
      rowId: 0,
      admin: '',
      roles: '',
      AssignRolesHandleClose () {
        AssignRolesObj.AssignRolesDialogVisible = false
      },
      AssignRolesSubmitClick () {
        console.log(selectData.selectValue)
        store.dispatch('usersModule/updateRoles', {id: AssignRolesObj.rowId, rid: selectData.selectValue}).then(() => store.dispatch('usersModule/getUsersPageData', { pageNum: pageData.pagenum, pageSize: pageData.pagesize }))
        AssignRolesObj.AssignRolesDialogVisible = false
      }
    })
    const selectData = reactive({
      selectValue: '',
      options: computed(() => objToArr(store.state.usersModule.rolesData))
    })
    return { tableInEvents, handleSizeChange, handleCurrentChange, pageData, userListData, findBtnClick, inputBlurEvent, AddUserData, addForm, addFormRules, addProductEvent, addFormRef, changeUsers, changeUsersForm, changeUsersFormRules, total, AssignRolesObj, selectData, contentList }
  }
})
</script>
